package main

import (
	"fmt"
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"my_iris/global"
	"my_iris/web"
	"os"
	"strconv"
)

// @title DEMO API
// @version 1.0
// @description DEMO API
// @description 提交方式基本都是form表单提交, 个别特别标明的以json提交
// @description http statusCode: 200-成功, {data: 返回结果, msg: 提示信息, errCode: 请无视}
// @description http statusCode: 400-失败, {msg: 错误信息, errCode: 错误码(0不用处理,非0情况需要区分处理)}
// @description http statusCode: 401-未登录
// @host
// @BasePath /
// @schemes https http

// @tags
// @tag.name 通用
// @tag.description 通用

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization

// @securityDefinitions.apikey ApiKeyAuthAdmin
// @in header
// @name Authorization
func main() {
	app := iris.New()
	// disable, fatal, error, warn, info, debug
	if global.SiteConf.IsProd {
		app.Logger().SetLevel("warn")
	} else {
		app.Logger().SetLevel("debug")
	}

	// 路由
	web.Routes(app)

	host := "0.0.0.0"
	port, _ := strconv.Atoi(os.Getenv("PORT"))
	if port < 80 || port > 65535 {
		port = 80
	}
	_ = app.Run(
		// Start the web server at host:port
		iris.Addr(fmt.Sprintf("%s:%d", host, port)),
		// withConf
		getWithConf(),
		// skip err server closed when CTRL/CMD+C pressed:
		iris.WithoutServerError(iris.ErrServerClosed),
		// enables faster json serialization and more:
		iris.WithOptimizations,
		iris.WithoutPathCorrectionRedirection, // 斜杠结尾的路由不自动重定向到不带斜杠的地址
	)
}

func getWithConf() (withConf iris.Configurator) {
	conf := iris.DefaultConfiguration()
	conf.FireMethodNotAllowed = true
	conf.DisableBodyConsumptionOnUnmarshal = true
	conf.RemoteAddrHeaders = map[string]bool{
		"X-Real-Ip":        false,
		"X-Forwarded-For":  true,
		"CF-Connecting-IP": true,
	}

	withConf = iris.WithConfiguration(conf)
	return
}

func init() {
	golog.SetPrefix("[myIris]")
	golog.Info("初始化conf.yml")
	// 初始化站点配置
	err := global.InitSiteConf()
	if err != nil {
		panic(err)
	}
	// 初始化redis连接池
	//rc := global.SiteConf.Redis
	//utils.InitRedisPool(rc.Host, rc.Port, rc.Password, rc.Database, rc.MaxIdle, rc.MaxActive)
	// 初始化 mongo 配置
	//mongoConf := global.SiteConf.Mongo
	//utils.InitMongoDB(mongoConf.Host, mongoConf.User, mongoConf.Password, mongoConf.Database)
	// 创建 tmp 目录, 0777
	err = os.MkdirAll("./tmp", os.ModePerm)
	if err != nil {
		golog.Warn("创建tmp目录: ", err)
	}
}
